import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:testlearn/entry/article_entity_entity.dart';
import 'package:testlearn/entry/banner_entity.dart';
import 'package:testlearn/res/strings.dart';
import 'package:testlearn/sparrow_dio/sparrow_dio.dart';
import 'package:testlearn/sparrow_dio/src/sparrow_dio.dart';

import 'package:testlearn/widget/my_phoenix_header.dart' as myPhoenixHeader;
import 'package:testlearn/widget/my_phoenix_footer.dart' as myPhoenixFooter;

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _result = "get 请求示例";

  //分页页数
  int _page = 0;

  List<BannerData> bannerDatas = [];

  List<ArticleEntityDataDatas> articleDatas = [];

  void _getBanner() async {
    _page = 0;
    _getUrl();
    getMoreData(_page);
  }

  SwiperController? _swiperController;

  Future _getUrl() async {
    Request.getCallback(
      YStrings.banner,
      data: {},
      queryParameters: {},
      complete: () {},
      success: (Response<dynamic> data) {
        var dataa = BannerEntity.fromJson(data.data);
        bannerDatas = dataa.data!;
        _result = data.data.toString();
        // _result = dataa.data.toString();
        setState(() {});

        print(_result);
      },
    );
  }

  Future getMoreData(int page) async {
    Request.getCallback(YStrings.ARTICLE_LIST + "$page/json", success: (data2) {
      var data = ArticleEntityEntity().fromJson(data2.data);
      if (page == 0) {
        articleDatas = data.data!.datas!;
      } else {
        articleDatas.addAll(data.data!.datas!);
      }
      setState(() {});
    }, error: (data) {});
  }

  @override
  void initState() {
    super.initState();
    _getBanner();
    _swiperController = SwiperController()..addListener(() {});
    _swiperController!.startAutoplay();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: EasyRefresh.custom(
        header: myPhoenixHeader.PhoenixHeader(),
        footer: myPhoenixFooter.PhoenixFooter(),
        slivers: <Widget>[
          SliverList(
              delegate: SliverChildBuilderDelegate((context, index) {
            if (index == 0) {
              return getBanner();
            } else if (index < articleDatas.length - 1) {
              return getRow(index);
            }
            return null;
          }, childCount: articleDatas.length + 1))
        ],
        onRefresh: () async {
          await Future.delayed(Duration(seconds: 1), () {
            setState(() {
              _page = 0;
            });
            _getBanner();
          });
        },
        onLoad: () async {
          await Future.delayed(Duration(seconds: 1), () {
            setState(() {
              _page++;
            });

            getMoreData(_page);
          });
        },
      ),
    );
  }

  Widget getBanner() {
    return Container(
      color: Colors.white60,
      width: MediaQuery.of(context).size.width,
      height: 200,
      child: Swiper(
        itemCount: bannerDatas.length,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                image: DecorationImage(
                    image: NetworkImage(bannerDatas[index].imagePath!))),
          );
        },
        loop: true,
        autoplay: true,
        autoplayDelay: 3000,
        autoplayDisableOnInteraction: true,
        pagination: SwiperPagination(
            builder: DotSwiperPaginationBuilder(size: 6, activeSize: 9)),
        viewportFraction: 0.8,
        scale: 0.9,
        onTap: (index) {
          //跳转页面
          print("点击了$index,${bannerDatas[index].url}");
        },
        controller: _swiperController,
      ),
    );
  }

  Widget getRow(int i) {
    return GestureDetector(
      child: Container(
          padding: EdgeInsets.symmetric(vertical: 10, horizontal: 5),
          child: ListTile(
            leading: IconButton(
              icon: articleDatas[i].collect!
                  ? Icon(
                      Icons.favorite,
                      color: Theme.of(context).primaryColor,
                    )
                  : Icon(Icons.favorite_border),
              tooltip: '收藏',
              onPressed: () {
                if (articleDatas[i].collect!) {
                  // cancelCollect(articleDatas[i].id);
                } else {
                  // addCollect(articleDatas[i].id);
                }
              },
            ),
            title: Text(
              articleDatas[i].title!,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
            subtitle: Padding(
              padding: EdgeInsets.only(top: 10.0),
              child: Row(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 6),
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: Theme.of(context).primaryColor,
                        width: 1.0,
                      ),
                      borderRadius: BorderRadius.circular((20.0)), // 圆角度
                    ),
                    child: Text(
                      articleDatas[i].superChapterName!,
                      style: TextStyle(color: Theme.of(context).primaryColor),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(left: 10),
                    child: Text(articleDatas[i].author!),
                  ),
                ],
              ),
            ),
            trailing: Icon(Icons.chevron_right),
          )),
      onTap: () {
        if (0 == 1) return;
        // Navigator.push(
        //   context,
        //   MaterialPageRoute(
        //     builder: (context) => ArticleDetail(
        //         title: articleDatas[i].title, url: articleDatas[i].link),
        //   ),
        // );
      },
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _swiperController!.stopAutoplay();
    _swiperController!.dispose();
    super.dispose();
  }
}
